package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 下单
     *
     * @param orders
     */
    @Transactional
    @Override
    public void submit(Orders orders) {
        //获取当前用户id
        Long currentId = BaseContext.getCurrentId();
        //购物车信息
        LambdaQueryWrapper<ShoppingCart> scLqw = new LambdaQueryWrapper<>();
        scLqw.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = shoppingCartService.list(scLqw);
        if (list == null || list.size() == 0){
            throw new CustomException("购物车为空,请先购物");
        }
        //地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null ){
            throw new CustomException("地址为空,请先添加地址");
        }
        //用户信息
        User user = userService.getById(currentId);
        if (user == null){
            throw new CustomException("用户为空");
        }


        //总金额
        AtomicInteger totalAmount = new AtomicInteger(0);//原子计数器
        //封装为List<OrderDetail>集合
        long id = IdWorker.getId();
        List<OrderDetail> orderDetails = list.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail,"id");
            orderDetail.setOrderId(id);

            //计算当前购物车的价格
            BigDecimal amount = shoppingCart.getAmount();
            Integer number = shoppingCart.getNumber();
            BigDecimal multiply = amount.multiply(new BigDecimal(number));
            totalAmount.addAndGet(multiply.intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //封装为Orders
        orders.setId(id);//id
        orders.setNumber(String.valueOf(id));//订单号
        orders.setStatus(2);//订单状态
        orders.setUserId(currentId);//下单用户id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//结账时间
        orders.setAmount(new BigDecimal(totalAmount.get()));//总金额
        orders.setUserName(user.getName());//用户名
        orders.setPhone(addressBook.getPhone() == null ? "" : addressBook.getPhone());//手机号
        orders.setAddress((addressBook.getProvinceName() == null ? "":addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "":addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "":addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "":addressBook.getDetail()));//地址
        orders.setConsignee(addressBook.getConsignee());//收货人
        //添加到订单表
        save(orders);
        //添加到订单明细表
        orderDetailService.saveBatch(orderDetails);
        //清空购物车
        shoppingCartService.remove(scLqw);
    }

    /**
     * 分页查询订单明细
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Transactional
    @Override
    public Page<OrdersDto> getOrderDetail(int page, int pageSize, Long number, LocalDateTime beginTime, LocalDateTime endTime) {
        //查询原始数据
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersLqw = new LambdaQueryWrapper<>();
        ordersLqw.eq(number != null,Orders::getNumber,number);
        if (beginTime!=null&&endTime!=null){
            ordersLqw.between(Orders::getOrderTime,beginTime,endTime);
        }
        ordersLqw.orderByDesc(Orders::getOrderTime);
        this.page(ordersPage,ordersLqw);


        //拷贝数据
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<Orders> orders = ordersPage.getRecords();
        List<OrdersDto> list = orders.stream().map(order -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);

            //获取用户名
            Long userId = order.getUserId();
            User user = userService.getById(userId);
            String name = user.getName();
            ordersDto.setUserName(name == null ? "无名人士" : name);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return ordersDtoPage;
    }
}
